package com.yociyy.security.authentication;

import java.util.*;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;

/**
 * Default implementation of {@link UserAuthenticationConverter}
 * 转换自定义用户信息
 *
 * @author: YoCiyy
 * @date: 2020/7/4
 */
public class YoCiUserAuthenticationConverter implements UserAuthenticationConverter {

	@Override
	public Map<String, ?> convertUserAuthentication(Authentication authentication) {
		Map<String, Object> response = new LinkedHashMap<String, Object>();
		response.put(USERNAME, authentication.getName());
		if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
			response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
		}
		return response;
	}

	@Override
	public Authentication extractAuthentication(Map<String, ?> map) {
		if (map.containsKey(USERNAME)) {
			Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
			// xxx 抽取常量，存在魔法值
			Long id = Long.valueOf(String.valueOf( map.get("id")));
			String username = (String) map.get("user_name");
			Long deptId = Long.valueOf(String.valueOf( map.get("deptId")));
			ArrayList<String> list = (ArrayList<String>) map.get("permissions");
			HashSet<String> permissions = new HashSet<>(list);
			YoCiUser user = new YoCiUser(id, deptId, permissions, username, "N/A", true, true, true, true, authorities);
            return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
		}
		return null;
	}

	private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
		Object authorities = map.get(AUTHORITIES);
		if (authorities instanceof String) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
		}
		if (authorities instanceof Collection) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
					.collectionToCommaDelimitedString((Collection<?>) authorities));
		}
		throw new IllegalArgumentException("Authorities must be either a String or a Collection");
	}
}
